import { Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { RuntimeException } from './runtime.exception';
import { EXCEPTION } from 'src/constants';

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    console.log(
      'common-api/src/exceptions/all-exceptions.filter.ts:9',
      exception,
    );
    // 如果是 RuntimeException 直接可以响应
    if (exception instanceof RuntimeException) {
      super.catch(exception, host);
      return;
    }
    // 否则，需要统一转换成 RuntimeException 再响应
    let message = '服务器未知错误';
    let code = EXCEPTION.SERVER_ERROR;
    if (exception instanceof HttpException) {
      // message: [ 'limit should not be empty', 'page should not be empty' ]
      const response = exception.getResponse();
      if (typeof response === 'string') {
        message = response;
      } else if ('message' in response) {
        if (Array.isArray(response.message)) {
          message = response.message.join('\n');
        } else {
          message = exception.message;
        }
      }
      code = exception.getStatus();
    } else if (exception?.message) {
      message = exception.message;
    }
    super.catch(new RuntimeException(message, code), host);
  }
}
